<template>
  <div class="fupan">
    <a-card :bordered="false" :body-style="{padding: '24px 0',marginTop:'24px'}">
      <div class="extra-wrap" slot="title">
        <a-date-picker v-model="date" :disabled-date="disabledDate" @change="getData" :allowClear="false" />
      </div>
      <div slot="extra"></div>
      <div class="wrap">
        <div id="main" style="height: 600px;"></div>
      </div>
    </a-card>
    <a-drawer
      title="上架商品详情"
      placement="right"
      :visible="visible"
      width="1200"
      @close="onClose"
    >
      <a-table
        rowKey="name"
        :columns="columns"
        :data-source="goods"
        :pagination="false"
        bordered
        size="middle"
      >
        <div slot="cover_img" slot-scope="cover_img">
          <img style="width: 96px;height: 96px;" :src="cover_img" alt="">
        </div>
      </a-table>
    </a-drawer>
  </div>
</template>

<script>
import moment from 'moment';
import {live_Minute_analysis} from '@/api/dianshang/dianshang'
import * as echarts from 'echarts';

export default {
  data() {
    return {
      date: moment(),
      chartTimeSelect: 1,
      labelAlign: 'right',
      loading: false,
      reloadTime: 60, // 自动刷新时间（秒）
      reloadChangeTime: 0,
      reloadIndex: null, // 用于关闭setInterval
      totalData: [],
      data: [],
      columns: [
        {
          title: '商品名',
          width: 160,
          dataIndex: 'name',
        },
        {
          title: '图片',
          dataIndex: 'cover_img',
          width: 100,
          scopedSlots: {
            customRender: 'cover_img',
          },
        },
        {
          title: '商品单价',
          width: 60,
          dataIndex: 'goods_price',
        },
        {
          title: '成单量',
          width: 60,
          dataIndex: 'sales_number',
          sorter: (a, b) => a.sales_number - b.sales_number,
        },
        {
          title: '销售额',
          width: 60,
          dataIndex: 'sales_money',
          sorter: (a, b) => a.sales_money - b.sales_money,
        },
      ],
      myChart: null,
      mod: 1, // 用于判断是否在shangjia的点上hover
      visible: false,
      goods: [],

    }
  },
  created() {
  },
  mounted() {
    this.createChart()
    this.$EventBus.$on('onresize', () => {
      this.myChart.resize()
    })
  },
  methods: {
    init() {
      this.getData()
    },
    getData() {
      this.loading = true
      const date = moment(this.date).format("YYYY-MM-DD")
      this.chartLoading()
      live_Minute_analysis({ date }).then((res_list) => {
        if (res_list.errcode == 0) {
          for (let o of res_list.data) {
            o.live_time = o.live_time.split(' ')[1] // 转换时间，只要 时:分
          }
          this.data = res_list.data
          this.setOptions(res_list.data)
        }
      }).catch(() => {
        this.chartHideLoading()
        this.loading = false
      });
    },
    createChart() {
      setTimeout(() => {
        var chartDom = document.getElementById('main');
        this.myChart = echarts.init(chartDom);
        this.setEvent()
        this.init()
      }, 0);
    },
    setOptions(data) {
      const _this = this
      const options = {
        animation: false,
        legend: {
          left: 'center',
          data: ['点击', '消耗', '点击单价', '客单价', '成单金额', '成单量', '观看人数']
        },
        tooltip: {
          trigger: 'axis',
          borderWidth: 1,
          borderColor: '#ccc',
          padding: 10,
          textStyle: {
            color: '#000'
          },
          formatter: function (params) {
            return _this.tooltipRender(params, data)
          }
        },
        axisPointer: {
          link: [
            {
              xAxisIndex: 'all'
            }
          ],
          label: {
            backgroundColor: '#777'
          }
        },
        grid: [
          {
            left: '10%',
            right: '8%',
            height: '50%'
          },
          {
            left: '10%',
            right: '8%',
            top: '63%',
            height: '16%'
          }
        ],
        xAxis: [
          {
            type: 'category',
            data: data.map(o=>o['live_time']),
            boundaryGap: false,
            axisLine: { onZero: false },
            splitLine: { show: false },
            min: 'dataMin',
            max: 'dataMax',
            axisPointer: {
              z: 100
            }
          },
          {
            type: 'category',
            gridIndex: 1,
            data: data.map(o=>o['live_time']),
            boundaryGap: false,
            offset:-48,
            axisLine: { 
              lineStyle:{
                width: 12,
                color: '#f5f5f5',
              }
            },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: { show: false },
          },
        ],
        yAxis: [
          {
            scale: true,
            splitArea: {
              show: true
            }
          },
          {
            scale: true,
            gridIndex: 1,
            splitNumber: 2,
            min: 1,
            name: '上架',
            nameLocation:'center',
            axisLabel: { show: false },
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: { show: false },
          }
        ],
        dataZoom: [
          {
            type: 'inside',
            xAxisIndex: [0, 1],
            start: 0,
            end: 100
          },
          {
            show: true,
            xAxisIndex: [0, 1],
            type: 'slider',
            top: '85%',
            start: 0,
            end: 100
          }
        ],
        series: [
          {
            name: '点击',
            type: 'line',
            data: data.map(o=>o['click']),
          },
          {
            name: '消耗',
            type: 'line',
            data: data.map(o=>o['cost']),
          },
          {
            name: '点击单价',
            type: 'line',
            data: data.map(o=>o['cpc']),
          },
          {
            name: '客单价',
            type: 'line',
            data: data.map(o=>o['cdprice']),
          },
          {
            name: '成单金额',
            type: 'line',
            data: data.map(o=>o['dsOcpcConversionsDetail80Amount']),
          },
          {
            name: '成单量',
            type: 'line',
            data: data.map(o=>o['dsOcpcConversionsDetail80']),
          },
          {
            name: '观看人数',
            type: 'line',
            data: data.map(o=>o['online_user']),
          },
          {
            name:'shangjia',
            type: 'effectScatter',
            xAxisIndex: 1,
            yAxisIndex: 1,
            symbolSize: 12,
            data: data.map(o => o['goods'].length != 0 ? 1 : ''),
            rippleEffect: {
              scale: 1,
              brushType: ''
            },
            itemStyle:{
              color:'#1890ff'
            },
          }
        ]
      }
      options && this.myChart.setOption(options);
      this.chartHideLoading()
    },
    tooltipRender(params, data) {
      let content = `<div class="dot" style="margin-bottom:-12px;color:#666666">${params[0].name}</div>` + "<br />";
      let o = data.find(e => e.live_time == params[0].name)
      if (this.mod == 1) { 
        for (let item of params) {
          if (item.componentSubType == 'effectScatter') {
            if (o['goods'].length != 0) {
              content += `
              <div style="display:flex;align-items: center;justify-content: space-between;margin-bottom: -12px;font-size:14px;">
                <span class="dot" style="color:#666666">上架商品：</span>`
              + o['goods'].length + "件</div><br />";
            }
          } else {
            content += `<div style="width:140px;margin-bottom: -12px;display:flex;align-items: center;justify-content: space-between;font-size:14px;">
              <div>
                <span style="display: inline-block;width:12px;height:12px;border-radius: 50%;background:${item.color}"></span> 
                <span class="dot" style="color:#666666">${item.seriesName}：</span>
              </div>
              `
              + item.data + "</div><br />"
          }
        }
      } else {
        content += `<div style="font-size:15px;font-weight:700;">上架了${o['goods'].length}件商品</div>`
        for (let item of o['goods'].slice(0,2)) {
          content += `<div style="max-width:260px;display:flex;flex-direction: column;">
              <div style="margin-top:6px;display:flex;flex-direction: column;">
                <div style="display:flex;align-items: center;">
                  <img src="${item.cover_img}" style="width:32px;height:32px;">
                  <div style="text-overflow: ellipsis;overflow: hidden;word-break: break-all;white-space: nowrap;width:200px;margin-left:10px;">${item.name}</div>
                </div>
                <div style="margin-top:10px;display:flex;align-items: center;justify-content: space-between;">
                  <div>￥${item.goods_price}</div>
                  <div><span style="color:#666666"> 本场销量：</span>${item.sales_number}</div>
                </div>
              </div>
            </div>`
        }
        if (o['goods'].length > 2) {
          content += `<div style="font-size:16px;">...</div>`
        }
      }
      return content
    },
    setEvent() {
      const _this = this
      this.myChart.on('mouseover', { seriesName: 'shangjia' }, function () {
        _this.mod = 2
      })
      this.myChart.on('mousemove', { seriesName: 'shangjia' }, function () {
        _this.mod = 2
      })
      this.myChart.on('mouseout', { seriesName: 'shangjia' }, function () {
        _this.mod = 1
      })
      this.myChart.on('click', { seriesName: 'shangjia' }, function (e) {
        let item = _this.data.find(o => o.live_time == e.name)
        _this.goods = item.goods
        _this.visible = true
      })
    },
    chartKeyFilter(key) {
      switch (key) {
        case 'click':
          return '点击';
        case 'cost':
          return '消耗'
        case 'cpc':
          return '点击单价'
        case 'cdprice':
          return '客单价'
        case 'dsOcpcConversionsDetail80':
          return '成单金额'
        case 'dsOcpcConversionsDetail80Amount':
          return '成单量'  
        default:
          return '无';
      }
    },
    chartLoading() {
      this.myChart.showLoading({
        text: 'loading',
      });
    },
    chartHideLoading() {
      this.myChart.hideLoading()
    },
    disabledDate(current){
      return current && ( current < moment().endOf('day').add(-100, 'days') || current > moment().endOf('day').add('days')) ;
    },
    onClose() {
      this.visible = false
    },
  },
  computed: {
    reloadPercent() {
      return Math.ceil(100 - (this.reloadChangeTime / this.reloadTime) * 100)
    }
  },
  beforeDestroy() {
    clearInterval(this.reloadIndex)
  },
  components:{
  }
}
</script>

<style lang="less" scoped>
.search{
  background-color: #ffffff;
  padding: 12px;
  border-radius: 8px;
  margin-top: 20px;
}
.reload{
  cursor: pointer;  
}
.fupan{
  overflow: hidden;
  .wrap{
    max-height: 750px;
    .table{
    }
    .total{
      overflow: hidden;
      .grid{
        display: flex;
        flex-direction: column;
        font-size: 16px;
        .label{
          margin-bottom: 10px;
        }
      }
    }
  }
}
</style>